import datetime
from multiprocessing import Lock

from tortoise.queryset import QuerySet
from tortoise.expressions import Q

from models import Project
from scheams import ProjectQuery
from core import config,get_logger


logger = get_logger(__name__)

number = None
lock = Lock()

async def createPoejectCode(project_group_name: str):
    """创建项目编码： 格式 YYYYMM-‘project_group_name’-XXXXXXXX

    Args:
        project_group_name (str): 项目评审组名称
    """
    
    date = datetime.datetime.now()
    
    global number
    
    with lock:
        if number is None:
            number = await Project.all().count()
            
        logger.debug(number)
            
        number += 1
        suffix = str(number).zfill(6)
    
    project_group_prefix = config.settings.ProjectGroupName(project_group_name).name
    res = "-".join([date.strftime('%Y%m'),project_group_prefix,suffix])
    logger.debug(res)
    return res

# if __name__ == "__main__":
#     print(createPoejectCode("test"))

def projectQueryBuiler(projectQuery: ProjectQuery, querySet: QuerySet) -> QuerySet:
    
    if projectQuery.statu :
        querySet = querySet.filter(statu=projectQuery.statu)
    
    if projectQuery.project_group :
        querySet = querySet.filter(project_group=projectQuery.project_group)
    
    if projectQuery.project_batch :
        querySet = querySet.filter(project_batch_id=projectQuery.project_batch)
        
    
    if projectQuery.query_str and projectQuery.query_str.strip():
        querySet = querySet.filter(Q(project_name__icontains=projectQuery.query_str.strip()) | Q(project_code__icontains=projectQuery.query_str.strip()))
        
    return querySet